package cn.melonlib.objects.maps;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.ObjectUtils;

import java.io.IOException;
import java.util.Map;

public class JsonMap<V> extends DataMap<String,V> {
    private final ObjectMapper jsonMapper=new ObjectMapper();

    public JsonMap(int initialCapacity, float loadFactor) {
        super(initialCapacity, loadFactor);
    }

    public JsonMap(int initialCapacity) {
        super(initialCapacity);
    }

    public JsonMap() {
    }

    public JsonMap(Map<? extends String, ? extends V> m) {
        super(m);
    }

    public JsonMap(String json) throws JsonParseException,
            JsonMappingException, IOException {
        Map<String, V> tmp = jsonMapper.readValue(json, new TypeReference<Map<String, V>>() {
        });
        for (String key : tmp.keySet()) {
            this.put(key, tmp.get(key));
        }
    }
    public static <V> JsonMap<V> createMap(){
        return new JsonMap<V>();
    }
    public static <V> JsonMap<V> createMap(int initialCapacity){
        return new JsonMap<V>(initialCapacity);
    }
    public static <V> JsonMap<V> createMap(String json)throws Exception{
        return new JsonMap<V>(json);
    }
    public static <V> JsonMap<V> createMap(Map<String,V> map){
        if(ObjectUtils.isEmpty(map)){
            return new JsonMap<V>();
        }
        return new JsonMap<V>(map);
    }

    public JsonMap(int initialCapacity, float loadFactor, boolean accessOrder) {
        super(initialCapacity, loadFactor, accessOrder);
    }

    public String jsonString() throws Exception {
        return jsonMapper.writeValueAsString(this);
    }

    public String jsonPettyString() throws Exception {
        return jsonMapper.writerWithDefaultPrettyPrinter().writeValueAsString(this);
    }

    public JsonMap<V> append(String k, V v) {
        super.put(k, v);
        return this;
    }
    public JsonMap<V> appendAll(JsonMap<V> data) {
        super.putAll(data);
        return this;
    }
}
